package com.hd.quartz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hd.quartz.common.FieldNameConstants;
import com.hd.quartz.common.PageUtils;
import com.hd.quartz.common.Query;
import com.hd.quartz.dao.ScheduleJobDao;
import com.hd.quartz.entity.ScheduleJobEntity;
import com.hd.quartz.service.ScheduleJobService;
import com.hd.quartz.util.Constant;
import com.hd.quartz.util.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <h3>partitionjob</h3>
 * <p>ScheduleJobServiceImpl</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2020-09-14 17:27
 **/
@Slf4j
@Service("scheduleJobService")
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobDao, ScheduleJobEntity>
        implements ScheduleJobService {

    @Autowired
    private Scheduler scheduler;

    //加载完后 初始化
    //项目启动时，初始化定时器
//    @PostConstruct
//    public void init() {
//        List<ScheduleJobEntity> jobEntityList = this.list();
//        for (ScheduleJobEntity entity : jobEntityList) {
//            CronTrigger trigger = ScheduleUtils.getCronTrigger(scheduler, entity.getJobId());
//            //如果不存在，则创建
//            if(trigger == null) {
//                ScheduleUtils.createScheduleJob(scheduler, entity);
//            } else {
//                ScheduleUtils.updateScheduleJob(scheduler, entity);
//            }
//        }
//    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String beanName = (String) params.get(FieldNameConstants.BEAN_NAME_KEY);

//        Page<ScheduleJobEntity> page = (Page<ScheduleJobEntity>) this.page(new Query<ScheduleJobEntity>(params).getPage(),
//                new QueryWrapper<ScheduleJobEntity>()
//                .like(StringUtils.isNotBlank(beanName), FieldNameConstants.FIELD_NAME_BEAN_NAME, beanName)
//                );
        IPage<ScheduleJobEntity> page = this.page(new Query<ScheduleJobEntity>(params).getPage(),
                new QueryWrapper<ScheduleJobEntity>()
                .like(StringUtils.isNotBlank(beanName), FieldNameConstants.FIELD_NAME_BEAN_NAME, beanName)
                );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ScheduleJobEntity scheduleJob) {
        log.info("[开始更新job: {}]", scheduleJob);
        try {
            //重新构建定时任务, 使得cron表达式生效
            ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            updateById(scheduleJob);
            log.info("[更新job成功]");
        } catch (Exception e) {
            log.error("更新失败: ", e);
        }
    }

    @Override
    public void deleteBatch(Long[] jobIds) {
        for (Long id : jobIds) {
            ScheduleUtils.deleteScheduleJob(scheduler, id);
        }
        //删除 批量
        this.removeByIds(Arrays.asList(jobIds));
    }

    @Override
    public int updateBatch(Long[] jobIds, int status) {
        return 0;
    }

    @Override
    public void run(Long[] jobIds) {

    }

    @Override
    public void pause(Long[] jobIds) {

    }

    @Override
    public void resume(Long[] jobIds) {

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveF(ScheduleJobEntity scheduleJob) {
        scheduleJob.setCreateTime(new Date());
        scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        try {
            this.save(scheduleJob);
            ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            log.info("[新增任务成功: {}]", scheduleJob);
        } catch (Exception e) {
            log.error("发生异常: ", e);
        }


    }
}
